<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>Expenditure Quarter</title>
	<style type="text/css">
        body {
            text-align: center;
            font: 10px sans-serif;
        }
        svg {
            font: 10px sans-serif;
        }
        .header {
            font: 15px sans-serif;
        }
        div.tooltip {
            position: absolute;
            text-align: left;
            padding: 8px;
            font: 10px sans-serif;
            background: #ddd;
            border: solid 1px #aaa;
            border-radius: 8px;
            /*pointer-events: none;*/
        }
        .node circle {
            fill: #fff;
            stroke: steelblue;
            stroke-width: 1.5px;
        }
        .node {
            font: 10px sans-serif;
        }
        .link {
            fill: none;
            stroke: #ccc;
            stroke-width: 1.5px;
        }
        
    </style>
    <script type="text/javascript" src="../js/d3.js"></script>
    <script type="text/javascript" src="../js/dimple.v2.1.0.js"></script>
    <script src="../js/pace/pace.js"></script>
    <link href="../js/pace/themes/loadingBar.css" rel="stylesheet" />
</head>
<body>
	<script type="text/javascript">
		d3.json("../XPD004Controller?p=initial",function(error,data){
			navigate();
			collapsibleTree(data);
		});
		
		function navigate(){
			var root = {"name":"งบประมาณ",
						"children":[{"name":"ปีงบประมาณ",
							"children":[{"name":"ประเภทงบประมาณ",
								"children":[{"name":"หน่วยงาน",
									"children":[{"name":"โครงการ",
										"children":[{"name":"กิจกรรม"}]
									}]
								}]
							}]
						}]
			};
			var width = 600;
			var height = 50;
			
			var cluster = d3.layout.cluster().size([height, width-160]);
			
			var diagonal = d3.svg.diagonal().projection(function(d) { return [d.y, d.x]; });
			
			var header = d3.select("body").append("div").attr("id","header").attr("class","header");
			header.html("<a href='../index.html'><img src='../images/home_icon.png'></a> รายงานงบประมาณ ตามไตรมาส มหาวิทยาลัยราชภัฏรำไพพรรณี <br/>");
			
			d3.select("body").append("div").attr("id","navigateGraph");
			var svg = d3.select("#navigateGraph").append("svg")
				.attr("width", width)
				.attr("height", height)
				.append("g")
				.attr("transform", "translate(60,0)");
			var nodes = cluster.nodes(root);
			var links = cluster.links(nodes);

			var link = svg.selectAll(".link")
				.data(links)
				.enter().append("path")
				.attr("class", "link")
				.attr("d", diagonal);

			var node = svg.selectAll(".node")
				.data(nodes)
				.enter().append("g")
				.attr("class", "node")
				.attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; })
			
				node.append("circle")
				.attr("r", 4.5);
			
			node.append("text")
			.attr("dx",15)
			//.attr("dx", function(d) { return d.children ? -8 : 8; })
			.attr("dy", -8)
			.style("text-anchor", "end")
			//.style("text-anchor", function(d) { return d.children ? "end" : "start"; })
			.text(function(d) { return d.name; });

			d3.select(self.frameElement).style("height", height + "px");
			
		}//end navigate
		
		function collapsibleTree(data) {
	        var margin = {
	                top: 20,
	                right: 120,
	                bottom: 20,
	                left: 120
	            },
	            width = 1500 - margin.right - margin.left,
	            height = 800 - margin.top - margin.bottom;

	        var i = 0,
	            duration = 750,
	            root;

	        var tree = d3.layout.tree()
	            .size([height, width]);

	        var diagonal = d3.svg.diagonal()
	            .projection(function (d) {
	                return [d.y, d.x];
	            });
	        var div = d3.select("body").append("div").attr("id", "treeGraph");
	        var svg = d3.select("#treeGraph").append("svg")
	            .attr("width", width + margin.right + margin.left)
	            .attr("height", height + margin.top + margin.bottom)
	            .append("g")
	            .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

	        //d3.json("../XPD002Controller?graphType=tree",function(error,data){
	        root = data;
	        root.x0 = height / 2;
	        root.y0 = 0;

	        function collapse(d) {
	            if (d.children) {
	                d._children = d.children;
	                d._children.forEach(collapse);
	                d.children = null;
	            }
	        }

	        root.children.forEach(collapse);
	        update(root);
	        //});//end d3.json

	        d3.select(self.frameElement).style("height", "1000px");
	       
	        function update(source) {

	            // Compute the new tree layout.
	            var nodes = tree.nodes(root).reverse();
	            var links = tree.links(nodes);

	            // Normalize for fixed-depth.
	            nodes.forEach(function (d) {
	                d.y = d.depth * 180;
	            });

	            // Update the nodes…
	            var node = svg.selectAll("g.node")
	                .data(nodes, function (d) {
	                    return d.id || (d.id = ++i);
	                });

	            // Enter any new nodes at the parent's previous position.
	            var nodeEnter = node.enter().append("g")
	                .attr("class", "node")
	                .attr("transform", function (d) {
	                    return "translate(" + source.y0 + "," + source.x0 + ")";
	                })
	                .on("click", click)
	                .on("mouseover", mouseover)
	                .on("mouseout", mouseout);

	            nodeEnter.append("circle")
	                .attr("r", 1e-6)
	                .style("fill", function (d) {
	                    return d._children ? "lightsteelblue" : "#fff";
	                });

	            nodeEnter.append("text")
	                .attr("x", function (d) {
	                    return d.children || d._children ? -10 : 10;
	                })
	                .attr("dy", ".35em")
	                .attr("text-anchor", function (d) {
	                	return d.children || d._children ? "end" : "start";
	                })
	                .html(function (d) {
	                	var x = 0;
	                	if(d.children || d._children){
	                		x = -10;
	                	}else{
	                		x = 10;
	                	}
	                	var t = ""+d.name;
	                	var length = 30;
	                	var y = 0.35;
						var name = "";
						while(t.length > length){
							name += "<tspan x=\""+x+"\" y=\"-3\" dy=\""+(y)+"em\">";
							name += t.substring(0,length);
							name += "</tspan>";
							y += 1.5;
							t = t.substring(length);
						}
						name += "<tspan x=\""+x+"\" y=\"-3\" dy=\""+(y)+"em\">";
						name += t;
						name += "</tspan>";
	                    return name;
	                })
	                .style("fill-opacity", 1e-6);

	            // Transition nodes to their new position.
	            var nodeUpdate = node.transition()
	                .duration(duration)
	                .attr("transform", function (d) {
	                    return "translate(" + d.y + "," + d.x + ")";
	                });

	            nodeUpdate.select("circle")
	                .attr("r", 4.5)
	                .style("fill", function (d) {
	                    return d._children ? "lightsteelblue" : "#fff";
	                });

	            nodeUpdate.select("text")
	                .style("fill-opacity", 1);

	            // Transition exiting nodes to the parent's new position.
	            var nodeExit = node.exit().transition()
	                .duration(duration)
	                .attr("transform", function (d) {
	                    return "translate(" + source.y + "," + source.x + ")";
	                })
	                .remove();

	            nodeExit.select("circle")
	                .attr("r", 1e-6);

	            nodeExit.select("text")
	                .style("fill-opacity", 1e-6);

	            // Update the links…
	            var link = svg.selectAll("path.link")
	                .data(links, function (d) {
	                    return d.target.id;
	                });

	            // Enter any new links at the parent's previous position.
	            link.enter().insert("path", "g")
	                .attr("class", "link")
	                .attr("d", function (d) {
	                    var o = {
	                        x: source.x0,
	                        y: source.y0
	                    };
	                    return diagonal({
	                        source: o,
	                        target: o
	                    });
	                });

	            // Transition links to their new position.
	            link.transition()
	                .duration(duration)
	                .attr("d", diagonal);

	            // Transition exiting nodes to the parent's new position.
	            link.exit().transition()
	                .duration(duration)
	                .attr("d", function (d) {
	                    var o = {
	                        x: source.x,
	                        y: source.y
	                    };
	                    return diagonal({
	                        source: o,
	                        target: o
	                    });
	                })
	                .remove();

	            // Stash the old positions for transition.
	            nodes.forEach(function (d) {
	                d.x0 = d.x;
	                d.y0 = d.y;
	            });
	            
	          
	            var max = Math.max.apply(Math,nodes.map(function(o){return o.depth;}));
	            var navi = d3.select("#navigateGraph").selectAll("g.node").selectAll("circle");
	            navi.forEach(function(d,i){
	            	if(i<=max){
	            		d[0].style.fill = "rgb(176,196,222)";
	            	} else{
	            		d[0].style.fill = "rgb(255,255,255)";
	            	}
	            });
	            
	        }//end update

	        // Toggle children on click.
	        function click(d) {
	            if (d.children) {
	                d._children = d.children;
	                d.children = null;
	            } else {
	                d.children = d._children;
	                d._children = null;
	            }
	            update(d);
	        }

	        // Toggle children on mouseover.
	        var tip = d3.select("body").append("div")
	            .attr("class", "tooltip")
	            .style("opacity", 1e-6);

	        function mouseover(d) {
	        	var textHtml = d.name + "<br/> จำนวนเงินที่อนุมิติ: " + d.currentBudget.toLocaleString("th-TH")
	        					+"<br/> จำนวนเงินที่เหลือ: " + (d.currentBudget - d.paySum).toLocaleString("th-TH");
	        	if(typeof d.budgetPeriodId != "undefined" && typeof d.activityId == 'undefined'){
	        		textHtml += ' <br/><a onclick="showBudgetQuarter('+d.budgetPeriodId+','+d.budgetGroupId+',\''+d.budgetGroupName+'\','+d.departmentId+',\''+d.departmentName+'\','+d.projectId+',\''+d.projectName+'\','+d.activityId+');" href="#">ข้อมูลรายไตรมาส</a>';
	        	}
	            tip.transition().duration(500).style("opacity", 1);
	            tip.transition().duration(200).style("opacity", 0.9);
	            tip.html(textHtml).style("left", (d3.event.pageX) + "px").style("top", (d3.event.pageY - 90) + "px");
	        }

	        function mouseout() {
	            //tip.transition().duration(500).style("opacity", 1e-6);
	        }
		} //end collapsibleTree
		
		function showBudgetQuarter(budgetPeriodId,budgetGroupId,budgetGroupName,departmentId,departmentName,projectId,projectName,activityId){
			removeDiv("barGraph");
			var text = "รายงานงบประมาณรายไตรมาส <br/>";
			if(budgetPeriodId != null){
				text += "ปี "+budgetPeriodId;
			}
			if(budgetGroupName !== "undefined"){
				text += " " +budgetGroupName;
			}
			if(departmentName !== "undefined"){
				text +=" "+departmentName
			}
			if(projectName !== "undefined"){
				text +=" "+projectName
			}
			//d3.select("body").append("div").attr("id","barGraph").append("div").html(text);
			d3.json("../XPD004Controller?p=drilldown&budgetPeriodId="+budgetPeriodId+
					"&budgetGroupId="+budgetGroupId+"&departmentId="+departmentId+
					"&projectId="+projectId+"&activityId="+activityId,function(error,data){
				if(typeof data != "undefined"){
					d3.select("body").append("div").attr("id","barGraph").append("div").attr("class","header").html(text);
					var svg = dimple.newSvg("#barGraph", 590, 400);
					var myChart = new dimple.chart(svg, data);
					myChart.setBounds(60, 30, 510, 330)
					var x = myChart.addCategoryAxis("x", ["quarter", "name"]);
					var y = myChart.addMeasureAxis("y", "amount");
					x.title = "ไตรมาส";
					y.title = "จำนวนเงิน";
					var chart = myChart.addSeries("name", dimple.plot.bar);
					
					chart.getTooltipText = function(e) {
	                     return [
	                         "ไตรมาส: " + e.x,
	                         "จำนวนเงิน: " + e.y.toLocaleString("th-TH") + " บาท"
	                     ];
	                 };
	                 
					var myLegend = myChart.addLegend(65, 10, 510, 20, "right");
					myChart.draw(600);
					
					var legendText = myLegend.shapes.selectAll("text");
					legendText.forEach(function(d,i){
						if(i==0){
							d[0].textContent = "จำนวนเงินที่เหลือ";
						}else{
							d[0].textContent = "จำนวนเงินที่ใช้";
						}
					});
					goToAnchor("barGraph");
				}else{
					d3.select("body").append("div").attr("id","barGraph").append("div").attr("class","header").text("ไม่มีข้อมูล");
				}
			});//end d3.json
		}//end showBudgetQuarter
		
		function removeDiv(divName){
			if(document.getElementById(divName)!=null){
				document.getElementById(divName).remove();
			}
		}
		
		function goToAnchor(name) {
            document.getElementById(name).scrollIntoView(true);
        }
		
	</script>
</body>
</html>